<template>
	<div class="ywgzt-container">
		<title-banner title="业务告警"></title-banner>
		<div class="content">
			<yd-form ref="myForm" :options="formOptions" :model="searchFormData" :btns="formBtns"></yd-form>
			<YdTable
				:formData="searchFormData"
				:tableConfig="tableConfig"
				:tableData="tableData"
				@sizeChangeHandler="searchHandler"
				@currentChangeHandler="searchHandler"
				@sortChangeHandler="searchHandler"
			></YdTable>
			<!-- 搜索条件 -->
			<el-row class="info-banner">
				<el-col :span="4" class="searchTitle">
					系统名称：
					<span :title="tableItemDetail.systemName">{{ tableItemDetail.systemName || '' }}</span>
				</el-col>
				<el-col :span="4" class="searchTitle">
					业务名称：
					<span :title="tableItemDetail.businessName">{{ tableItemDetail.businessName || '' }}</span>
				</el-col>
				<el-col :span="4" class="searchTitle">
					告警指标：
					<span>{{ formatAlarmIndicator(tableItemDetail.alarmIndicatorCode) || '' }}</span>
				</el-col>
				<el-col :span="12" class="searchTitle">
					<yd-form ref="myForm2" :options="formOptions2" :model="searchFormData2" :btns="formBtns2"></yd-form>
				</el-col>
			</el-row>
			<YdTable
				:formData="searchFormData2"
				:tableConfig="detailTableConfig"
				:tableData="tableData2"
				@sizeChangeHandler="queryGrid2"
				@currentChangeHandler="queryGrid2"
				@sortChangeHandler="queryGrid2"
			></YdTable>
		</div>
	</div>
</template>

<script setup name="AlarmBusinessEvent" lang="tsx">
import TitleBanner from '@/views/ops-workbench/components/TitleBanner/index.vue';
import { parseTime, downloadFromBlob } from '@/utils/common';
import {
	getBusinessAlarmList,
	getRealTimeAlarmDetailList,
	getRealTimeAlarmDetailListExport,
} from '@/api/ops-workbench/index-more/alarmServiceEventFiles';
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import useCurrentInstance from '@/utils/useCurrentInstance';
import { saveAs } from 'file-saver';

const { proxy } = useCurrentInstance();
const router = useRouter();
const route = useRoute();

const currentTime = new Date();
const endTime = parseTime(currentTime, '{y}-{m}-{d} {h}:{i}:00');
const past1h = currentTime.setHours(currentTime.getHours() - 1);
const searchFormData = reactive({
	systemId: route.query.systemId,
	businessCode: route.query.businessCodeList ? route.query.businessCodeList : '',
	startTime: parseTime(past1h, '{y}-{m}-{d} {h}:{i}:00'),
	endTime: endTime,
});
// 上 表
const formOptions = reactive<FormOptionType>([
	{
		type: 'select',
		label: '系统名称',
		prop: 'systemId',
		span: 6,
		selectKey: 'value',
		api: {
			name: 'queryAppSystemOptions',
			params: { isStatus: 1 },
		},
		cascaders: [
			{
				cascadersParams: 'businessCode',
				api: {
					name: 'queryBusinessOptions',
				},
			},
		],
	},
	{
		type: 'select',
		label: '业务名称',
		prop: 'businessCode',
		selectKey: 'value',
		attrs: {
			// multiple: true,
			indeterminate: false,
		},
	},
	{
		type: 'date-picker',
		label: '时间范围',
		prop: 'dateRange',
		span: 9,
		dateType: 'datetimerange',
		shortcutsKeys: ['today', 'lastDay', 'lastWeek'],
		defaulShortcutsKey: 'last1h',
	},
]);

// 下 详情表
const formOptions2 = reactive<FormOptionType>([
	{
		type: 'date-picker',
		label: '时间范围',
		prop: 'dateRange',
		span: 18,
		dateType: 'datetimerange',
		shortcutsKeys: ['today', 'lastDay', 'lastWeek'],
		enableCrossDay: true,
		defaulShortcutsKey: 'last1h',
	},
]);
const formBtns = reactive<BtnType[]>([
	{
		type: 'primary',
		text: '查询',
		handler: searchHandler,
	},
]);
const formBtns2 = reactive<BtnType[]>([
	{
		type: 'primary',
		text: '查询',
		handler: queryGrid2,
	},
	{
		type: 'primary',
		text: '导出',
		handler: handleExportDetail,
	},
]);
// 下-详情表表单参数
const searchFormData2: anyObj = reactive({
	pageSize: 10,
	pageNum: 1,
	orderByColumn: 'cycleTime',
	isAsc: 'desc',
});

// 上下表级联参数
const tableItemDetail: anyObj = reactive({
	businessName: '',
	businessCode: '',
	systemId: '',
	systemName: '',
	alarmIndicatorCode: '',
});
let tableData = ref([]);
let tableData2 = ref([]);
const tableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '业务名称',
			prop: 'businessName',
		},
		{
			label: '健康度',
			prop: 'healthRate',
			formatter: (row: anyObj, val: ApiVal) => {
				if (val !== '' && val !== undefined && val !== null) {
					return val + '%';
				}
				return val;
			},
			sortable: true,
		},
		{
			label: '总告警次数',
			prop: 'alarmNum',
			sortable: true,
		},
		{
			label: '健康度低告警次数',
			prop: 'healthAlarmCount',
			operation: [
				{
					text: undefined,
					rowKey: 'healthAlarmCount',
					handler: (scope: anyObj) => {
						handleDetailFormInited(scope.row, 'BS_FAIL_RATE_30');
					},
				},
			],
			sortable: true,
		},
		{
			label: '失败率高告警次数',
			prop: 'failAlarmCount',
			operation: [
				{
					text: undefined,
					rowKey: 'failAlarmCount',
					handler: (scope: anyObj) => {
						handleDetailFormInited(scope.row, 'BS_FAIL_RATE_10');
					},
				},
			],
			sortable: true,
		},
		{
			label: '响应慢告警次数',
			prop: 'dealTimeAlarmCount',
			operation: [
				{
					text: undefined,
					rowKey: 'dealTimeAlarmCount',
					handler: (scope: anyObj) => {
						handleDetailFormInited(scope.row, 'BS_FAIL_RATE_20');
					},
				},
			],
			sortable: true,
		},
		// {
		// 	label: '响应慢事件档案数',
		// 	prop: 'dealTimeEventFileCount',
		// 	sortable: true,
		// 	operation: [
		// 		{
		// 			rowKey: 'dealTimeEventFileCount',
		// 			handler: (scope: anyObj) => {
		// 				// searchFormData2.selectSystemId = scope.row.id;
		// 				(searchFormData2.dataTypeName = '响应慢业务'), (searchFormData2.alarmIndicatorCode = 'BS_FAIL_RATE_20'), handleAlarmDetail(scope.row);
		// 			},
		// 		},
		// 	],
		// },
	],
	pagination: {
		orderByColumn: 'healthRate',
		isAsc: 'desc',
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	loading: true,
});

const downloadLoading = ref(false);
const detailTableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '告警时间',
			prop: 'cycleTime',
			formatter: (row: anyObj, val: any) => {
				return val ? val.substr(0, 19) : val;
			},
			sortable: true,
		},
		{
			label: '总访问量',
			prop: 'count',
			sortable: true,
		},
		{
			label: '告警访问量',
			prop: 'alarmCount',
			renderXss: (row: TableOptionType, val: ApiVal) => {
				return <span style="color: #ff9a0c">{val}</span>;
			},
			sortable: true,
		},
		{
			label: '响应慢访问量',
			prop: 'dealTimeAlarmCount',
			sortable: true,
			hide: false,
		},
		{
			label: '失败访问量',
			prop: 'failCount',
			renderXss: (row: anyObj, val: ApiVal) => {
				return <span style="color: #ff5d84">{val}</span>;
			},
			sortable: true,
		},
		{
			label: '失败率',
			prop: 'failRate',
			formatter: (row: anyObj, val: ApiVal) => {
				return val !== null ? val + '%' : val;
			},
			sortable: true,
		},
		{
			label: '健康度',
			prop: 'healthRate',
			formatter: (row: anyObj, val: ApiVal) => {
				if (val !== '' && val !== undefined && val !== null) {
					return val + '%';
				}
				return val;
			},
			sortable: true,
			hide: false,
		},
		{
			label: '响应慢比例',
			prop: 'dealTimeAlarmRate',
			formatter: (row: anyObj, val: ApiVal) => {
				return val !== null ? val + '%' : val;
			},
			sortable: true,
			hide: false,
		},
		{
			label: '操作',
			prop: '',
			operation: [
				{
					text: '告警分析',
					handler: (scope: anyObj) => {
						getAlarmDetail(scope.row);
					},
				},
			],
		},
	],
	pagination: {
		pageSize: 10,
		pageNum: 1,
		total: 0,
	},
	loading: false,
});

const downloadLoading2 = ref(false);

onMounted(() => {
	searchHandler();
});
// 上方表查询
function searchHandler() {
	tableConfig.loading = true;
	tableData2.value = [];
	resetObj(tableItemDetail);
	let forData = {
		...searchFormData,
		busiType: route.query.notKeyBusi == 'true' ? 0 : 1,
	};
	getBusinessAlarmList(forData).then((res: ApiResponse) => {
		console.log(res, 'kankan res');
		tableConfig.loading = false;
		if (res.code !== 0) {
			proxy.$modal.msgError(res.msg);
			return;
		}
		tableConfig.pagination!.total = res.data.total;
		tableData.value = res.data.data;
		if (res.data.total > 0) {
			let obj = res.data.data[0];
			if (obj instanceof Object) {
				for (let key in obj) {
					tableItemDetail[key] = obj[key];
				}
			}
			console.log(tableItemDetail, tableItemDetail.systemName, 'tableItemDetail是什么');
			// 默认排在第一个的健康度告警指标
			tableItemDetail.alarmIndicatorCode = 'BS_FAIL_RATE_30';
			changeColHide(tableItemDetail.alarmIndicatorCode);

			queryGrid2();
		} else {
			detailTableConfig.pagination!.total = 0;
			tableData2.value = [];
		}
	});
}
// 详情
function queryGrid2() {
	detailTableConfig.loading = true;
	let formData = {
		...tableItemDetail,
		...searchFormData2,
	};
	getRealTimeAlarmDetailList(formData).then((res: ApiResponse) => {
		detailTableConfig.loading = false;
		if (res.code !== 0) {
			proxy.$modal.msgError(res.msg);
			return;
		}
		detailTableConfig.pagination!.total = res.data.total;
		tableData2.value = res.data.data;
	});
}

// 获取跳转类型
function getAlarmType(val: string): string {
	let jumpId = '';
	switch (val) {
		case 'BS_FAIL_RATE_10':
			jumpId = '2';
			break;
		case 'BS_FAIL_RATE_20':
			jumpId = '1';
			break;
		case 'BS_FAIL_RATE_30':
			jumpId = '3';
			break;
		default:
			jumpId = '1';
	}
	return jumpId;
}
// 告警分析-跳转
function getAlarmDetail(obj: anyObj) {
	obj.titleName =
		tableItemDetail.systemName + '-' + tableItemDetail.businessName + '-' + formatAlarmIndicator(tableItemDetail.alarmIndicatorCode) + '分析';
	obj.systemId = tableItemDetail.systemId;
	obj.businessCode = tableItemDetail.businessCode;
	obj.startTime = obj.cycleTime;
	let jumpId = getAlarmType(tableItemDetail.alarmIndicatorCode);
	obj.trendId = jumpId;
	obj.areaId = jumpId;
	console.log(obj, 'oobbjj', obj.endTime);
	router.push({
		path: '/ops-workbench/business-alarm-analysis/index',
		query: {
			...obj,
			// id: obj.id,
			// systemId: obj.systemId,
			systemName: tableItemDetail.systemName,
			// businessCode: obj.businessCode,
			businessName: tableItemDetail.businessName,
			// cycleTime: obj.cycleTime,
			// startTime: 'obj.startTime',
			// endTime: 'obj.endTime',
			// titleName: obj.titleName,
			// trendId: obj.trendId,
			// areaId: obj.areaId,
			// groupId: obj.groupId,
			alarmIndicatorCode: tableItemDetail.alarmIndicatorCode,
			// dataType: obj.dataType,
		},
	});
}
function resetObj(obj: anyObj) {
	for (let key in obj) {
		obj[key] = '';
	}
}
// 告警指标选项
const alarmIndicatorOptions: anyObj = ref([
	{ value: 'BS_FAIL_RATE_10', label: '失败率高告警' },
	{ value: 'BS_FAIL_RATE_20', label: '响应慢告警' },
	{ value: 'BS_FAIL_RATE_30', label: '健康度低告警' },
]);
// 格式化告警指标
function formatAlarmIndicator(val: ApiVal): string {
	console.log('formatAlarmIndicator', val);
	let labelName = '';
	if (val) {
		labelName = alarmIndicatorOptions.value.find((op: { value: string | number }) => op.value === val).label || '';
	}
	return labelName;
}
// 改变列的可见属性hide
function changeColHide(alarmIndicatorCode: ApiVal) {
	if (alarmIndicatorCode === 'BS_FAIL_RATE_20') {
		let healthRate: any = detailTableConfig.columns.find((col: anyObj) => col.prop === 'healthRate') ?? '';
		healthRate.hide = true;
		let dealTimeAlarmCount: any = detailTableConfig.columns.find((col: anyObj) => col.prop === 'dealTimeAlarmCount') ?? '';
		dealTimeAlarmCount.hide = false;
		let dealTimeAlarmRate: any = detailTableConfig.columns.find((col: anyObj) => col.prop === 'dealTimeAlarmRate') ?? '';
		dealTimeAlarmRate.hide = false;
	} else if (alarmIndicatorCode === 'BS_FAIL_RATE_30') {
		let healthRate: any = detailTableConfig.columns.find((col: any) => col.prop === 'healthRate') ?? '';
		healthRate.hide = false;
		let dealTimeAlarmCount: any = detailTableConfig.columns.find((col: anyObj) => col.prop === 'dealTimeAlarmCount') ?? '';
		dealTimeAlarmCount.hide = true;
		let dealTimeAlarmRate: any = detailTableConfig.columns.find((col: anyObj) => col.prop === 'dealTimeAlarmRate') ?? '';
		dealTimeAlarmRate.hide = true;
	} else {
		let healthRate: any = detailTableConfig.columns.find((col: any) => col.prop === 'healthRate') ?? '';
		healthRate.hide = true;
		let dealTimeAlarmCount: any = detailTableConfig.columns.find((col: anyObj) => col.prop === 'dealTimeAlarmCount') ?? '';
		dealTimeAlarmCount.hide = true;
		let dealTimeAlarmRate: any = detailTableConfig.columns.find((col: anyObj) => col.prop === 'dealTimeAlarmRate') ?? '';
		dealTimeAlarmRate.hide = true;
	}
}
function handleDetailFormInited(obj: anyObj, alarmCode: string) {
	let detailForm = JSON.parse(JSON.stringify(obj));
	detailForm.alarmIndicatorCode = alarmCode;

	if (detailForm instanceof Object) {
		for (let key in obj) {
			tableItemDetail[key] = detailForm[key];
		}
	}
	tableItemDetail.alarmIndicatorCode = alarmCode;
	changeColHide(alarmCode);
	tableItemDetail.pageNum = 1;
	queryGrid2();
}
// 详情列表-导出
function handleExportDetail() {
	let d: anyObj = JSON.parse(JSON.stringify(searchFormData2));
	d.pageNum = undefined;
	d.pageSize = undefined;
	d.alarmIndicatorName = formatAlarmIndicator(tableItemDetail.alarmIndicatorCode);
	d.alarmIndicatorCode = tableItemDetail.alarmIndicatorCode;
	d.systemId = tableItemDetail.systemId;
	d.systemName = tableItemDetail.systemName;
	d.businessCode = tableItemDetail.businessCode;
	d.businessName = tableItemDetail.businessName;
	let excelTitle = '';
	if (route.query.notKeyBusi == 'true') {
		excelTitle =
			'系统业务告警' +
			d.alarmIndicatorName.substring(0, 3) +
			'状况总览表' +
			d.startTime.replace(/\D/g, '') +
			'-' +
			d.endTime.replace(/\D/g, '') +
			'.xlsx';
	} else {
		excelTitle =
			'系统关键业务' +
			d.alarmIndicatorName.substring(0, 3) +
			'状况总览表' +
			d.startTime.replace(/\D/g, '') +
			'-' +
			d.endTime.replace(/\D/g, '') +
			'.xlsx';
	}
	downloadLoading2.value = true;
	getRealTimeAlarmDetailListExport(d).then((res: any): void => {
		downloadLoading2.value = false;
		let blob = new Blob([res], {
			type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8',
		});
		saveAs(blob, excelTitle);
	});
}
</script>

<style scoped lang="scss">
@import '@/styles/ops-workbench/common.scss';
@import '@/styles/ops-workbench/yd-table.scss';
.ywgzt-container {
	min-width: 1440px;
	min-height: 100vh !important;
	padding: 20px;
	:deep(.el-form-item__label) {
		color: #fff !important;
	}
	.info-banner {
		padding-left: 18px;
		.searchTitle {
			font-size: 15px;
			line-height: 28px;
			color: #ffffff;
			// font-weight: 900;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
		}
	}
}
</style>
